package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.exception.CartExceptionHandler;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.to.UserInfoTo;
import com.atguigu.gulimall.cart.vo.CartItemVo;
import com.atguigu.gulimall.cart.vo.CartVo;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import static com.atguigu.common.constant.CartConstant.CART_PREFIX;

@Service("cartService")
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;


    @Override
    public CartVo getCart() throws ExecutionException, InterruptedException {
        CartVo cartVo = new CartVo();
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        if (userInfoTo.getUserId() != null) {
            //1、登录
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            //临时购物车的键
            String temptCartKey = CART_PREFIX + userInfoTo.getUserKey();

            //2、如果临时购物车的数据还未进行合并
            List<CartItemVo> tempCartItems = getCartItems(temptCartKey);
            if (tempCartItems != null) {
                //临时购物车有数据需要进行合并操作
                for (CartItemVo item : tempCartItems) {
                    addCartService(item.getSkuId(),item.getCount());
                }
                //清除临时购物车的数据
                clearCartInfo(temptCartKey);
            }

            //3、获取登录后的购物车数据【包含合并过来的临时购物车的数据和登录后购物车的数据】
            List<CartItemVo> cartItems = getCartItems(cartKey);
            cartVo.setItems(cartItems);

        } else {
            //没登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            //获取临时购物车里面的所有购物项
            List<CartItemVo> cartItems = getCartItems(cartKey);
            cartVo.setItems(cartItems);
        }

        return cartVo;
    }

    /**
     * 清楚购物车
     *
     * @param temptCartKey
     */
    private void clearCartInfo(String temptCartKey) {
        redisTemplate.delete(temptCartKey);
    }

    /**
     * 获取缓存中的购物车
     *
     * @param temptCartKey
     * @return
     */
    private List<CartItemVo> getCartItems(String temptCartKey) {
        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(temptCartKey);
        List<Object> values = ops.values();
        if(values != null && values.size()>0){
            List<CartItemVo> cartItemVoStream = values.stream().map((obj) -> {
                CartItemVo cartItemVo = JSON.parseObject(obj.toString(), CartItemVo.class);

                return cartItemVo;
            }).collect(Collectors.toList());

            return cartItemVoStream;
        }

        return null;
    }

    @Override
    public CartItemVo addCartService(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOpt();
        String productRedisStr = (String)cartOps.get(skuId.toString());
        //判断redis购物车是否有该商品
        if(StringUtils.isEmpty(productRedisStr)){
            CartItemVo cartItemVo = new CartItemVo();
            CompletableFuture<Void> getSkuInfoFuture = CompletableFuture.runAsync(() -> {
                //1、远程查询当前要添加商品的信息
                R productSkuInfo = productFeignService.getInfo(skuId);
                SkuInfoVo skuInfo = productSkuInfo.getData(new TypeReference<SkuInfoVo>() {
                });
                //新增赋值给redis
                cartItemVo.setSkuId(skuInfo.getSkuId());
                cartItemVo.setTitle(skuInfo.getSkuTitle());
                cartItemVo.setImage(skuInfo.getSkuDefaultImg());
                cartItemVo.setPrice(skuInfo.getPrice());
                cartItemVo.setCount(num);
            }, executor);

            CompletableFuture<Void> getSkuAttrValuesFuture = CompletableFuture.runAsync(() -> {
                //2、远程查询skuAttrValues组合信息
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItemVo.setSkuAttrValues(skuSaleAttrValues);
            }, executor);

            //等待所有的异步任务全部完成
            CompletableFuture.allOf(getSkuInfoFuture, getSkuAttrValuesFuture).get();
            String cartItemJson = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(), cartItemJson);

            return cartItemVo;
        }else{//存在则改变商品数量
            CartItemVo cartItemVo = JSON.parseObject(productRedisStr, CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount() + num);
            String cartItemJson = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(),cartItemJson);

            return cartItemVo;
        }
    }

    @Override
    public CartItemVo getCartItem(Long skuId) {
        //拿到要操作的购物车信息
        BoundHashOperations<String, Object, Object> cartOps = getCartOpt();

        String redisValue = (String) cartOps.get(skuId.toString());

        CartItemVo cartItemVo = JSON.parseObject(redisValue, CartItemVo.class);

        return cartItemVo;
    }

    /**
     * 获取购物车
     *
     * @return
     */
    @Override
    public List<CartItemVo> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        List<CartItemVo> cartItemVoList = new ArrayList<>();
        if(userInfoTo==null){
            return null;
        }else{
            String userKey = CART_PREFIX + userInfoTo.getUserId();
            System.out.println(userKey);
            List<CartItemVo> cartItems = getCartItems(userKey);
            if(cartItems==null){
                throw new CartExceptionHandler();
            }else{
                cartItemVoList = cartItems.stream()
                        .filter(item -> item.getCheck())
                        .map((item) -> {
                            //更新为最新的价格（查询数据库）
                            R data = productFeignService.getPrice(item.getSkuId());
                            String price = data.getData(new TypeReference<String>() {
                            });
                            item.setPrice(new BigDecimal(price));
                            return item;
                        }).collect(Collectors.toList());
            }
        }
        return cartItemVoList;
    }

    /**
     * 判断是获取临时购物车还是登录时的购物车
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOpt() {
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        String cartKey = "";
        if(userInfoTo.getUserId() != null){
            cartKey = CART_PREFIX + userInfoTo.getUserId();//登录的
        }else{
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }

        //使用hash形式
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);

        return operations;
    }
}
